package com.app.weather.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.app.weather.data.WeatherDataSource;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;
import com.app.weather.Mapp;
import com.app.weather.R;
import com.app.weather.bean.City;
import com.app.weather.data.CityDataSource;
import com.app.weather.utils.SizeUtils;
import com.app.weather.utils.ToastUtils;
import com.app.weather.utils.WeatherUtils;

public class MainActivity extends BaseActivity {

    private static final int REQUEST_CHOOSE_CITY = 1;

    private LinearLayout positionLinearLayout;//位置布局控件
    private TextView positionTextView;//位置文本控件
    private TextView futureTextView;//未来天气按钮控件
    private LinearLayout contentLinearLayout;//内容布局控件
    private ImageView weatherImageView;//天气图片控件
    private TextView weatherTextView;//天气文本控件
    private TextView temperatureTextView;//温度文本控件
    private TextView windDirTextView;//风向文本控件
    private TextView windSpeedTextView;//风速文本控件
    private TextView humidityTextView;//湿度文本控件
    private TextView precipTextView;//降水量文本控件

    private CityDataSource cityDataSource;//城市数据源
    private WeatherDataSource weatherDataSource;//天气数据源

    private City city;//当前选中的城市

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();
        setView();
        getWeatherNow();
    }

    /**
     * 后一个页面回传的处理
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case REQUEST_CHOOSE_CITY: {
                if (resultCode == RESULT_OK) {
                    String locationId = data.getStringExtra("city");

                    cityDataSource.saveLastCity(locationId);
                    city = cityDataSource.selectOne(locationId);

                    //刷新数据
                    setView();
                    getWeatherNow();
                }
            }
            break;

        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        cityDataSource = Mapp.getInstance().getCityDataSource();
        weatherDataSource = Mapp.getInstance().getWeatherDataSource();

        //获取最近操作的城市，如果没有则获取城市列表的第一个
        String locationId = cityDataSource.getLastCity();
        city = TextUtils.isEmpty(locationId) ? null : cityDataSource.selectOne(locationId);
        if (city == null) {
            city = cityDataSource.selectList().get(0);
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        positionLinearLayout = findViewById(R.id.position_linearLayout);
        positionTextView = findViewById(R.id.position_textView);
        futureTextView = findViewById(R.id.future_textView);
        contentLinearLayout = findViewById(R.id.content_linearLayout);
        weatherImageView = findViewById(R.id.weather_imageView);
        weatherTextView = findViewById(R.id.weather_textView);
        temperatureTextView = findViewById(R.id.temperature_textView);
        windDirTextView = findViewById(R.id.windDir_textView);
        windSpeedTextView = findViewById(R.id.windSpeed_textView);
        humidityTextView = findViewById(R.id.humidity_textView);
        precipTextView = findViewById(R.id.precip_textView);
    }

    /**
     * 设置控件
     */
    private void setView() {
        positionLinearLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = CityCollectionActivity.buildIntent(MainActivity.this);
                startActivityForResult(intent, REQUEST_CHOOSE_CITY);
            }

        });

        positionTextView.setText(city.getLocationNameZH());

        futureTextView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = WeatherFutureActivity.buildIntent(MainActivity.this, city.getLocationID());
                startActivity(intent);
            }

        });
    }

    /**
     * 获取实时天气
     */
    private void getWeatherNow() {
        showLoadingDialog();
        weatherDataSource.getWeatherNow(this, city.getLocationID(), new QWeather.OnResultWeatherNowListener() {

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                contentLinearLayout.setVisibility(View.VISIBLE);
                dismissLoadingDialog();
                if (weatherBean.getCode() == Code.OK) {
                    WeatherNowBean.NowBaseBean nowBaseBean = weatherBean.getNow();

                    //设置天气动画图标
                    int icon = WeatherUtils.getIcon(nowBaseBean.getIcon());
                    weatherImageView.setImageResource(icon);

                    //设置天气名称
                    weatherTextView.setText(nowBaseBean.getText());

                    //设置温度
                    SpannableStringBuilder temperatureBuilder = new SpannableStringBuilder(nowBaseBean.getTemp() + "°C");
                    temperatureBuilder.setSpan(new AbsoluteSizeSpan(SizeUtils.sp2px(30)), nowBaseBean.getTemp().length(), temperatureBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    temperatureTextView.setText(temperatureBuilder);

                    //设置风向
                    windDirTextView.setText(nowBaseBean.getWindDir());

                    //设置风速
                    windSpeedTextView.setText(nowBaseBean.getWindSpeed() + "km/h");

                    //设置相对湿度
                    humidityTextView.setText(nowBaseBean.getHumidity() + "%");

                    //设置降水量
                    precipTextView.setText(nowBaseBean.getPrecip() + "mm");

                } else {
                    ToastUtils.showShort(weatherBean.getCode().getTxt());
                }
            }

            @Override
            public void onError(Throwable e) {
                contentLinearLayout.setVisibility(View.INVISIBLE);
                dismissLoadingDialog();
                ToastUtils.showShort(e.getMessage());
            }

        });
    }

}